import React, { Component } from "react";
import PropTypes from "prop-types";
import { nanoid } from "nanoid";

import "./index.css";

export default class Header extends Component {
  static propTypes = {
    addTodo: PropTypes.func.isRequired,
  };

  // 键盘事件的回调
  handleKeyUp = (event) => {
    // 解构赋值获取target, keyCode
    const { target, keyCode } = event;
    // 解构赋值获取从父组件传递过来的函数
    const { addTodo } = this.props;
    if (keyCode !== 13) return;
    // 添加内容不能为空
    if (target.value === "") return alert("输入错误");
    const tudoObj = { id: nanoid(), name: target.value, done: false };
    addTodo(tudoObj);
    target.value = "";
  };
  render() {
    return (
      <div className="todo-header">
        <input
          onKeyUp={this.handleKeyUp}
          type="text"
          placeholder="请输入你的任务名称，按回车键确认"
        />
      </div>
    );
  }
}
